<template>
    <div>
        <Form
            ref="entityForm"
            class="page-sys-user-drawer-form"
            :model="entity"
            :rules="entityRules"
            :disabled="drawerType === 'read'"
            label-position="top"
            label-colon
            hide-required-mark
        >
            <Row :gutter="32">
                <Col span="12">
                    <FormItem prop="name" label="姓">
                        <Input
                            v-model="entity.name"
                            placeholder="请输入姓，必填"
                        />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem prop="lastName" label="名">
                        <Input
                            v-model="entity.lastName"
                            placeholder="请输入名，必填"
                        />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="用户账号">
                        <Input
                            readonly
                            v-model="entity.account"
                            @on-blur="handAccountBlur"
                            placeholder="用户账号系统自动生成"
                        />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem prop="sex" label="性别">
                        <Select v-model.number="entity.sex">
                            <Option :value="1">男</Option>
                            <Option :value="0">女</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem prop="idCardNO" label="身份证号">
                        <Input
                            v-model="entity.idCardNO"
                            placeholder="请输入身份证号"
                        />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem prop="phone" label="手机号">
                        <Input
                            v-model="entity.phone"
                            placeholder="请输入手机号"
                        />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem prop="tel" label="座机">
                        <Input
                            v-model="entity.tel"
                            placeholder="请输入座机"
                        />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem prop="email" label="邮箱">
                        <Input
                            v-model="entity.email"
                            placeholder="请输入邮箱"
                        />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem prop="status" label="人员状态">
                        <Select v-model.number="entity.status">
                            <Option :value="1">正常</Option>
                            <Option :value="0">停用</Option>
                        </Select>
                    </FormItem>
                </Col>
            </Row>
            <Card :bordered="false" dis-hover title="岗位信息" class="ivu-mt i-table-no-border positionInfo">
                <Table :data="entity.positionList" :columns="columns">
                    <template slot-scope="{ row, index }" slot="orgId">
                        <Select ref="drpOrg" :transfer="true" v-model="row.orgId"  @on-change="handOrgChange" :label-in-value="true" v-if="editIndex === index">
                            <Option v-for="item in orgDataSource" :value="item.id" :key="item.id">{{item.name}}</Option>
                        </Select>
                        <span v-else>{{ row.orgName }}</span>
                    </template>
                    <template slot-scope="{ row, index }" slot="positionId">
                        <Select ref="drpPosition" :transfer="true" v-model="row.positionId"  v-if="editIndex === index">
                            <Option v-for="item in positionDataSource" :value="item.id" :key="item.id">{{item.name}}</Option>
                        </Select>
                        <span v-else>{{ row.positionName }}</span>
                    </template>
                    <template slot-scope="{ row, index }" slot="action">
                        <div v-if="editIndex === index">
                            <Button @click="handleSave(index)" type="success" ghost size="small">
                                <template v-if="!addNew">保存</template>
                                <template v-else>添加</template>
                            </Button>
                            <Button @click="handleCancel" v-if="!addNew" :disabled="addNew" type="primary" ghost size="small" class="ivu-ml">取消</Button>
                            <Button @click="handleDelete(index)" v-else type="error" ghost size="small" class="ivu-ml">删除</Button>
                        </div>
                        <div v-else>
                            <Button @click="handleEdit(index)" :disabled="addNew" type="primary" ghost size="small">编辑</Button>
                            <Poptip
                                confirm
                                transfer
                                title="是否要删除此行？"
                                @on-ok="handleDelete(index)">
                                <Button :disabled="addNew" type="error" ghost size="small" class="ivu-ml">删除</Button>
                            </Poptip>
                        </div>
                    </template>
                </Table>
                <Button :disabled="addNew" type="dashed" long icon="md-add" class="ivu-mt" @click="handleAdd">新增岗位</Button>
            </Card>
        </Form>
        <div class="page-sys-user-drawer-footer" v-if="drawerType != 'read'">
            <Button
                type="primary"
                @click="handleSubmitEdit"
                :loading="submitting"
                >提交</Button
            >
        </div>
    </div>
</template>
<script>
    import { mapState } from "vuex";
    import { SaveData, GetData, AccountExists } from "@api/user";
    import { OrgDataSource } from '@api/org';
    import { PositionDataSource } from '@api/position';

    export default {
        name: "table-form",
        props: {
            entityId: String,
            drawerType: String
        },
        data() {
            return {
                submitting: false,
                addNew: false,
                editIndex:-1,
                entity: {
                    id: null,
                    account: "",
                    password: "",
                    name: "",
                    lastName:"",
                    sex: 1,
                    idCardNO: "",
                    phone: "",
                    tel: "",
                    email: "",
                    status: 1,
                    positionList:[]
                },
                entityRules: {
                    lastName: [
                        {
                            required: true,
                            message: "请输入名",
                            trigger: "blur"
                        }
                    ],
                    name: [
                        { required: true, message: "请输入姓", trigger: "blur" }
                    ]
                },
                columns: [
                    {
                        title: '所属组织',
                        slot: 'orgId',
                        minWidth: 120
                    },
                    {
                        title: '岗位',
                        slot: 'positionId',
                        width: 100
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        align: 'center',
                        width: 140
                    }
                ],
                orgDataSource:[
                    {id:'',name:'',disabled:false}
                ],
                positionDataSource:[
                    {id:'',name:''}
                ]
            };
        },
        computed: {
            ...mapState("admin/layout", ["isMobile"]),
            labelWidth() {
                return this.isMobile ? undefined : 100;
            },
            labelPosition() {
                return this.isMobile ? "top" : "right";
            }
        },
        methods: {
            initEntity() {
                GetData(this.entityId).then(res => {
                    if (res.errcode != 0) {
                        this.$Message.error(res.msg);
                        return;
                    }
                    this.entity = res.data;
                });
            },
            handleSubmitEdit() {
                this.$refs.entityForm.validate(valid => {
                    if (valid) {
                        if (this.submitting) return;
                        this.submitting = true;

                        this.entity.positionList.forEach(item=>{
                            if(!item.id){
                                delete item.id;
                            }
                        });

                        SaveData(this.entity).then(res => {
                            this.submitting = false;
                            if (res.errcode != 0) {
                                this.$Message.error(res.msg);
                                return;
                            }
                            this.$emit("saveFinished");
                        }).catch(error=>{
                            this.submitting = false;
                        });
                    }
                });
            },
            handleSave (index) {
                let row=this.entity.positionList[index];
                let orgId=this.$refs.drpOrg.value;
                let orgName=this.$refs.drpOrg.query;
                let positionId=this.$refs.drpPosition.value;
                let positionName=this.$refs.drpPosition.query;
                if (!orgId || !positionId) {
                    this.$Message.error('请选择岗位！');
                    return;
                }
                row.orgId=orgId;
                row.orgName=orgName;
                row.positionId=positionId;
                row.positionName=positionName;
                this.editIndex = -1;
                this.addNew = false;
            },
            handleCancel () {
                this.editIndex = -1;
                this.addNew = false;
            },
            handleEdit (index) {
                let row=this.entity.positionList[index];
                let orgId=row.orgId;
                if(orgId){
                    PositionDataSource(orgId).then(res=>{
                        if(res.errcode!=0){
                            this.$Message.errcode(res.msg);
                            return;
                        }
                        this.positionDataSource=res.data;
                        this.editIndex = index;
                    })
                }
                else{
                    this.editIndex = index;
                }
            },
            handleDelete (index) {
                this.entity.positionList.splice(index, 1);
                this.addNew = false;
            },
            handleAdd(){
                this.addNew = true;
                const row = {
                    id: '',
                    orgId: '',
                    positionId: ''
                };
                this.entity.positionList.push(row);
                this.handleEdit(this.entity.positionList.length - 1);
            },
            handOrgChange(item){
                let orgId=item.value;
                PositionDataSource(orgId).then(res=>{
                    if(res.errcode!=0){
                        this.$Message.errcode(res.msg);
                        return;
                    }
                    this.positionDataSource=res.data;
                    this.$refs.drpPosition.clearSingleSelect();
                })
            },
            handAccountBlur(){
                let account=this.entity.account;
                if(account){
                    AccountExists(account).then(res=>{
                        if (res.errcode != 0) {
                            this.$Message.error(res.msg);
                            return;
                        }
                        if(res.data){
                            this.$Message.error("账号已存在！");
                            return;
                        }
                    });
                }
            }
        },
        created(){
            OrgDataSource().then(res=>{
                if(res.errcode!=0){
                    this.$Message.errcode(res.msg);
                    return;
                }
                this.orgDataSource=res.data;
            });
        },
        mounted() {
            if (this.entityId) this.initEntity();
        }
    };
</script>
<style>
    .positionInfo .ivu-table-cell{padding-left:3px;padding-right:3px;}
</style>